<template>
  <div class="ticket-detail-container">
    <h2 class="page-title">电子票详情</h2>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="10" animated />
    </div>
    
    <div v-else-if="ticketInfo">
      <el-card class="ticket-card">
        <template #header>
          <div class="card-header">
            <span>电子票信息</span>
            <div class="card-header-right">
              <el-button 
                v-if="canMarkAsUsed" 
                type="primary" 
                size="small" 
                :loading="markingAsUsed"
                @click="handleMarkAsUsed">
                使用票据
              </el-button>
              <el-tag v-if="isEventEnded && ticketInfo.status === 0" type="warning" style="margin-right: 10px;">
                活动已结束
              </el-tag>
              <el-tag :type="getTicketStatusType(ticketInfo.status)">
                {{ getTicketStatusText(ticketInfo.status) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <div class="ticket-content">
          <!-- 票券基本信息 -->
          <div class="ticket-basic-info">
            <div class="info-item">
              <label>票券编号：</label>
              <span>{{ ticketInfo.ticketCode }}</span>
            </div>
            <div class="info-item">
              <label>票种名称：</label>
              <span>{{ ticketInfo.ticketTypeName }}</span>
            </div>
            <div class="info-item">
              <label>票价：</label>
              <span class="price">¥ {{ (ticketInfo.price / 100).toFixed(2) }}</span>
            </div>
          </div>
          
          <el-divider content-position="left">活动信息</el-divider>
          
          <!-- 活动信息 -->
          <div class="event-info">
            <h3 class="event-title">{{ ticketInfo.eventName }}</h3>
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDateTime(ticketInfo.eventStartTime) }} ~ {{ formatDateTime(ticketInfo.eventEndTime) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span>{{ ticketInfo.eventVenue }}</span>
            </div>
          </div>
          
          <el-divider content-position="left">验票二维码</el-divider>
          
          <!-- 二维码区域 -->
          <div class="qrcode-section">
            <div v-if="ticketInfo.status === 0" class="qrcode-container">
              <div class="ticket-code-display">
                <h3>票券码</h3>
                <div class="ticket-code">{{ ticketInfo.ticketCode }}</div>
              </div>
              <p class="qrcode-tip">请向工作人员出示此票券码进行验票</p>
            </div>
            <div v-else-if="ticketInfo.status === 1" class="ticket-used">
              <el-result icon="success" title="已使用" sub-title="该票券已被使用" />
              <div class="used-info" v-if="ticketInfo.useTime">
                <p>使用时间：{{ formatDateTime(ticketInfo.useTime) }}</p>
              </div>
              <div class="questionnaire-button">
                <el-button 
                  v-if="ticketInfo.questionnaireAnswered === 0 || ticketInfo.questionnaireAnswered === undefined || ticketInfo.questionnaireAnswered === null" 
                  type="primary" 
                  @click="goToQuestionnaire">
                  填写活动问卷
                </el-button>
                <el-button 
                  v-else-if="ticketInfo.questionnaireAnswered === 1" 
                  type="success" 
                  disabled>
                  已完成活动问卷
                </el-button>
              </div>
            </div>
            <div v-else-if="ticketInfo.status === 3" class="ticket-cancelled">
              <el-result icon="error" title="已取消" sub-title="该票券已被取消" />
            </div>
          </div>
          
          <el-divider content-position="left">入场须知</el-divider>
          
          <!-- 入场须知 -->
          <div class="notice-section">
            <div class="notice-content" v-if="eventNotice">
              {{ eventNotice }}
            </div>
            <div v-else class="no-notice">
              <el-empty description="暂无入场须知" />
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <div v-else class="no-ticket">
      <el-empty description="未找到票券信息" />
    </div>
    
    <div class="back-button">
      <el-button @click="goBack">返回列表</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Location } from '@element-plus/icons-vue'
import { getTicketDetail, markTicketAsUsed } from '@/api/order'
import { getRandomEventQuestionnaire } from '@/api/questionnaire'

const route = useRoute()
const router = useRouter()
const ticketId = route.query.id

// 票券信息
const ticketInfo = ref(null)
// 加载状态
const loading = ref(true)
// 标记为已使用状态
const markingAsUsed = ref(false)
// 入场须知（可在此设置默认内容）
const eventNotice = computed(() => {
  return `1. 请妥善保管好您的电子票，不要泄露票据信息和二维码
2. 一张票仅限一人使用，二维码重复扫描无效
3. 活动开始前30分钟开始检票入场
4. 迟到观众将在合适时机安排入场，可能无法保证原座位
5. 活动期间请遵循工作人员引导，保持场内秩序`
})

// 判断活动是否已结束
const isEventEnded = computed(() => {
  if (!ticketInfo.value || !ticketInfo.value.eventEndTime) {
    return false;
  }
  
  try {
    const now = new Date();
    const endTime = new Date(ticketInfo.value.eventEndTime);
    
    if (!isNaN(endTime.getTime())) {
      return now > endTime;
    }
    return false;
  } catch (error) {
    console.error('判断活动是否结束出错:', error);
    return false;
  }
})

// 判断是否可以标记为已使用
const canMarkAsUsed = computed(() => {
  if (!ticketInfo.value) {
    console.log('票券信息未加载，无法显示标记按钮');
    return false;
  }
  
  // 确保状态值转为数字进行比较
  const status = parseInt(ticketInfo.value.status);
  
  // 1. 只有状态为"有效"(0)的票才能标记为已使用
  if (status !== 0) {
    console.log('票券状态不是未使用(0)，当前状态:', status);
    return false;
  }
  
  // 2. 活动结束后的票不能标记为已使用
  if (isEventEnded.value) {
    console.log('活动已结束，无法标记为已使用');
    return false;
  }
  
  return true;
})

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未设置'
  
  // 处理ISO格式的日期字符串
  const dateObj = new Date(dateTimeStr)
  return dateObj.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 获取票券详情
const fetchTicketDetail = async () => {
  if (!ticketId) {
    ElMessage.error('未指定票券ID')
    router.push('/front/user/tickets')
    return
  }
  
  console.log('正在获取票券详情，ID:', ticketId);
  loading.value = true
  try {
    const res = await getTicketDetail(ticketId)
    console.log('电子票详情响应:', res)
    
    if (res.code === 200 && res.data) {
      ticketInfo.value = res.data
      // 检查日期格式是否正确
      console.log('处理后的电子票详情:', JSON.stringify(ticketInfo.value))
      console.log('票券状态:', ticketInfo.value.status, '类型:', typeof ticketInfo.value.status)
      console.log('活动结束时间:', ticketInfo.value.eventEndTime)
    } else {
      ElMessage.error('获取票券详情失败')
    }
  } catch (error) {
    console.error('获取票券详情出错:', error)
    ElMessage.error('获取票券详情失败')
  } finally {
    loading.value = false
  }
}

// 标记电子票为已使用
const handleMarkAsUsed = async () => {
  // 二次确认
  try {
    await ElMessageBox.confirm(
      '确定要将此电子票标记为已使用吗？此操作不可撤销。',
      '标记确认',
      {
        confirmButtonText: '确定标记',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    markingAsUsed.value = true
    try {
      const res = await markTicketAsUsed(ticketId)
      
      if (res.code === 200) {
        ElMessage.success('电子票已成功标记为已使用')
        // 更新票券状态
        if (ticketInfo.value) {
          ticketInfo.value.status = 1
          ticketInfo.value.useTime = new Date().toISOString()
        }
      } else {
        ElMessage.error(res.msg || '标记失败')
      }
    } catch (error) {
      console.error('标记电子票出错:', error)
      ElMessage.error('标记失败，请稍后重试')
    } finally {
      markingAsUsed.value = false
    }
  } catch {
    // 用户取消操作
  }
}

// 获取电子票状态类型
const getTicketStatusType = (status) => {
  switch (status) {
    case 0: return 'success' // 未使用
    case 1: return 'info' // 已使用
    case 3: return 'danger' // 已取消
    default: return 'info'
  }
}

// 获取电子票状态文本
const getTicketStatusText = (status) => {
  switch (status) {
    case 0: return '未使用'
    case 1: return '已使用'
    case 3: return '已取消'
    default: return '未知状态'
  }
}

// 返回列表
const goBack = () => {
  router.push('/front/user/tickets')
}

// 前往问卷页面
const goToQuestionnaire = async () => {
  if (!ticketInfo.value || !ticketInfo.value.eventId) {
    ElMessage.error('无法获取活动信息')
    return
  }
  
  try {
    const eventId = ticketInfo.value.eventId
    const res = await getRandomEventQuestionnaire(eventId)
    
    if (res.code === 200 && res.data) {
      // 从返回的完整问卷数据中获取问卷ID
      const questionnaireId = res.data.id
      // 使用前台专用的问卷填写路由
      router.push(`/front/questionnaire/${eventId}?id=${questionnaireId}&from=ticket-detail&ticketId=${ticketId}`)
    } else {
      ElMessage.warning(res.msg || '该活动暂无问卷')
    }
  } catch (error) {
    console.error('获取问卷出错:', error)
    ElMessage.error('获取问卷失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchTicketDetail()
})
</script>

<style scoped>
.ticket-detail-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ticket-basic-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.event-info {
  margin-bottom: 20px;
}

.event-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #303133;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  line-height: 24px;
}

.info-item label {
  color: #606266;
  width: 80px;
  text-align: right;
  margin-right: 10px;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.qrcode-section {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.ticket-code-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 250px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.ticket-code {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-top: 10px;
  letter-spacing: 1px;
  user-select: all;
}

.qrcode-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.ticket-used, .ticket-cancelled {
  width: 100%;
}

.used-info, .cancel-info {
  text-align: center;
  color: #909399;
  margin-top: 10px;
}

.notice-section {
  margin-bottom: 30px;
}

.notice-content {
  white-space: pre-line;
  line-height: 1.6;
  color: #606266;
}

.back-button {
  margin-top: 20px;
  text-align: center;
}

.questionnaire-button {
  margin-top: 20px;
  text-align: center;
}

.no-ticket {
  padding: 40px 0;
  text-align: center;
}
</style> 